﻿using com.uplus.common;
using com.uplus.log4net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebApi.Bill.Biz;
using WebApi.Models;

namespace WebApi.Common
{
    public class PbxTool
    {
        //public static string serverUrl = BizBase.Get<BizConstant>().GetSValueInfo("SIPServer").SValueInfo;// "192.168.1.115:8089";
       // private static string serverUrl = AppConfigurtaion.GetSecondSection("SIPSetting", "Server");// "192.168.1.115:8089";
        public static string cookie { get; set; }
        public static string serverUrl { get; set; }
        #region PBX登录
        public static bool PbxLogin()
        {
            ResponseData responseCookData = new ResponseData();
            bool result = false;
            try
            {
                string url = $"https://{serverUrl}/api?";
                HttpMgr httpMgr = new HttpMgr();
                HttpMgr httpMgr1 = new HttpMgr();
                Dictionary<string, string> header = new Dictionary<string, string>();
                //header.Add("Content-Type", "application/json");


                RequestData requestData = new RequestData
                {
                    action = "challenge",
                    user = "cdrapi",
                    version = "1.0"
                };
                RequestSendData requestSendData = new RequestSendData
                {
                    request = requestData
                };
                byte[] dataByte = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(requestSendData));
                string res = "";
                byte[] r = httpMgr.PostDataByte(header, dataByte, url, "application/json", "utf-8", "application/json");
                if (r?.Length != 0)
                {
                    res = Encoding.UTF8.GetString(r);
                    JObject jo = JObject.Parse(res);
                    RequestLogin responseData = new RequestLogin
                    {
                        token = DataConvert.Md5($"{jo["response"]["challenge"].ToString()}cdrapi123", 32, true),
                        action = "login",
                        user = "cdrapi"
                    };
                    RequestSendLoginData requestSendLoginData = new RequestSendLoginData
                    {
                        request = responseData
                    };

                    byte[] dataSendByte = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(requestSendLoginData));

                    byte[] responseLogin = httpMgr1.PostDataByte(header, dataSendByte, url, "application/json", "utf-8", "application/json");
                    if (responseLogin != null)
                    {
                        res = Encoding.UTF8.GetString(responseLogin);
                        responseCookData = JsonConvert.DeserializeObject<ResponseData>(res);
                        if (responseCookData.status == 0)
                        {
                            cookie = responseCookData.response.cookie;
                            result = true;

                            Log4Helper.Debug("", "PbxTool.LoginTelPhonePBX已登录成功,获取cookie: " + cookie, null);
                            Log4Helper.Debug("", "PbxTool.LoginTelPhonePBX已登录成功！", null);
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                Log4Helper.Debug("", "PbxTool.LoginTelPhonePBX登录失败！", ex);
            }

            return result;
        }
        #endregion

        #region PBX登出
        public static bool PbxLogout()
        {
            bool result = false;
            try
            {
                string url = $"https://{serverUrl}/api?";
                HttpMgr httpMgr = new HttpMgr();

                Dictionary<string, string> header = new Dictionary<string, string>();
                RequestOut responseData = new RequestOut
                {
                    action = "logout",
                    cookie = cookie
                };
                RequestOutData requestSendLogOutData = new RequestOutData
                {
                    request = responseData
                };
                byte[] dataSendByte = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(requestSendLogOutData));
                string res = "";
                httpMgr.PostDataComplete += delegate (object s, byte[] responseLogin, int responseLoginTime, Exception exLogin)
                {
                    if (responseLogin != null)
                    {
                        res = Encoding.UTF8.GetString(responseLogin);
                        JObject jo = JObject.Parse(res);
                        if (jo["status"].ToString() == "0")
                        {
                            //this.Dispatcher.Invoke((Action)(() =>
                            //{
                            //    txtLog_Copy.Text = "PBX已退出";
                            //    txtLog_Copy.Foreground = new SolidColorBrush(Colors.Red);
                            //}));

                            result = true;
                            Log4Helper.Debug("", "PbxTool.LoginTelPhonePBX已退出成功！", null);
                        }

                    }
                };
                httpMgr.PostData(header, dataSendByte, url, "application/json", "UTF-8", "application/json");
            }
            catch (Exception ex)
            {
                //this.Dispatcher.Invoke((Action)(() =>
                //{
                //    txtLog_Copy.Text = ex.ToString();
                //    txtLog_Copy.Foreground = new SolidColorBrush(Colors.Red);
                //}));
                Log4Helper.Debug("", "PbxTool.LoginTelPhonePBX退出失败！" , null);
            }
            return result;
        }
        #endregion

        #region 获取所有分机信息
        public static List<Account> GetListAccount()
        {
            List<Account> listAccount = new List<Account>();
            try
            {
                
                while (!string.IsNullOrEmpty(cookie))
                {
                    string url = $"https://{serverUrl}/api?";
                    HttpMgr httpMgr = new HttpMgr();
                    HttpMgr httpMgr1 = new HttpMgr();
                    Dictionary<string, string> header = new Dictionary<string, string>();
                    RequestListAccounts responseData = new RequestListAccounts
                    {
                        action = "listAccount",
                        //cookie = responseCookData.response.cookie,
                        cookie = cookie,
                        item_num = "300",
                        options = "extension,account_type,fullname,status,addr",
                        page = "1",
                        sidx = "extension",
                        sord = "asc"
                    };
                    RequestListAccountsData requestSendLogOutData = new RequestListAccountsData
                    {
                        request = responseData
                    };
                    string res = "";
                    byte[] dataSendByte = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(requestSendLogOutData));
                    byte[] r = httpMgr.PostDataByte(header, dataSendByte, url, "application/json", "utf-8", "application/json");
                    if (r?.Length != 0)
                    {
                        res = Encoding.UTF8.GetString(r);

                        ResponseListAccountsData model = JsonConvert.DeserializeObject<ResponseListAccountsData>(res);
                       listAccount = model.response.account;
                       
                    }
                    break;
                }
               
            }
            catch (Exception ex)
            {
                Log4Helper.Debug("", "PbxTool.ListAccount 话机同步账号失败！", ex);
            }
            return listAccount;
        }
        #endregion
      

        public class RequestData
        {
            /// <summary>
            /// 
            /// </summary>
            public string action { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string user { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string version { get; set; }
        }

        public class RequestSendData
        {
            /// <summary>
            /// 
            /// </summary>
            public RequestData request { get; set; }

        }
        public class ResponseData
        {
            /// <summary>
            /// 
            /// </summary>
            public Cookie response { get; set; }
            public int status { get; set; }

        }
        public class Cookie
        {
            /// <summary>
            /// 
            /// </summary>
            public string cookie { get; set; }

        }
        public class RequestLogin
        {
            /// <summary>
            /// 
            /// </summary>
            public string action { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string token { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string user { get; set; }
        }
        public class RequestSendLoginData
        {
            /// <summary>
            /// 
            /// </summary>
            public RequestLogin request { get; set; }

        }


        public class RequestOut
        {
            /// <summary>
            /// 
            /// </summary>
            public string action { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string cookie { get; set; }
        }
        public class RequestOutData
        {
            /// <summary>
            /// 
            /// </summary>
            public RequestOut request { get; set; }

        }
        public class RequestTra
        {
            /// <summary>
            /// 
            /// </summary>
            public string action { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string cookie { get; set; }
            public string extension { get; set; }
            public string cfu { get; set; }

        }
        public class RequestTraData
        {
            /// <summary>
            /// 
            /// </summary>
            public RequestTra request { get; set; }

        }
        public class RequestApply
        {
            /// <summary>
            /// 
            /// </summary>
            public string action { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string cookie { get; set; }
        }
        public class RequestApplyData
        {
            /// <summary>
            /// 
            /// </summary>
            public RequestApply request { get; set; }

        }



        /// <summary>
        /// 获取单个分机号密码的入参类
        /// </summary>
        public class RequestSIPAccount
        {
            /// <summary>
            /// 
            /// </summary>
            public string action { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string cookie { get; set; }

            public string extension { get; set; }

            public string permission { get; set; }


            public string secret { get; set; }


        }
        public class RequestSIPAccountData
        {
            /// <summary>
            /// 
            /// </summary>
            public RequestSIPAccount request { get; set; }

        }

        //同步单个分机号密码
        public class ResponseSIPAccount
        {
            /// <summary>
            /// 分机号类
            /// </summary>
            public Extension extension { get; set; }


        }
        //分机号类
        public class Extension
        {
            /// <summary>
            /// 分机号
            /// </summary>
            public string extension { get; set; }

            public string permission { get; set; }
            /// <summary>
            /// 分机号密码
            /// </summary>
            public string secret { get; set; }
        }
        public class ResponseSIPAccountData
        {
            public ResponseSIPAccount response { get; set; }
        }

        /// <summary>
        /// 获取所有分机号的数据model
        /// </summary>
        public class RequestListAccounts
        {
            /// <summary>
            /// 
            /// </summary>
            public string action { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string cookie { get; set; }
            public string item_num { get; set; }

            public string options { get; set; }

            public string page { get; set; }

            public string sidx { get; set; }

            public string sord { get; set; }

        }
        public class RequestListAccountsData
        {
            /// <summary>
            /// 
            /// </summary>
            public RequestListAccounts request { get; set; }

        }


        /// <summary>
        /// 获取所有分机号的数据model
        /// </summary>
        public class ResponseListAccounts
        {
            /// <summary>
            /// 
            /// </summary>
            public List<Account> account = new List<Account>();

        }

        public class Account
        {
            private string account_type { get; set; }
            public string addr { get; set; }
            public string extension { get; set; }//分机号
            public string fullname { get; set; }
            public string status { get; set; }//Unavailable
        }
        public class ResponseListAccountsData
        {
            /// <summary>
            /// 
            /// </summary>
            public ResponseListAccounts response { get; set; }

        }
    }
}
